package com.example.springsecuritydemo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springsecuritydemo.entity.Users;
import com.example.springsecuritydemo.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authorization.AuthorityAuthorizationDecision;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 朱学鑫
 * @projectName springSecurity-Demo
 * @description: 自定义实现类方式验证用户名密码
 * @date 2022年02月22日 17:03
 */
@Service("userDetailsService")
public class MyUSerDetailService implements UserDetailsService {

    @Autowired
    private UsersMapper usersMapper;
    /**
     * 用户名密码验证方法(可以加上数据库验证)
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1.调用mapper方法查询数据库根据用户名
        QueryWrapper wrapper = new QueryWrapper();
        // where username = ?
        wrapper.eq("username",username);
        Users users = usersMapper.selectOne(wrapper);
        // 判断
        if (users == null) {
            throw  new UsernameNotFoundException("用户名不存在！");
        }
        List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        return new User(users.getUsername(),new BCryptPasswordEncoder().encode(users.getPassword()),authorities);
    }
}
